<?php

class RevendaController extends Site_Controller_Action
{
    
    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/revenda.js');
        
        $uf = trim($this->_getParam('estado', ''));
        $this->view->uf = $uf;
        
        $cid = trim($this->_getParam('cidade', ''));
        $this->view->cidade = $cid;
        
        //$query = 'SELECT SQL_CACHE EST_ID,EST_UF FROM ESTADOS ORDER BY EST_UF ASC';
        $query = 'SELECT SQL_CACHE distinct(e.EST_ID),e.EST_UF '
                .' FROM ESTADOS e, REVENDA r '
                .' WHERE e.EST_ID = r.EST_ID'
                .' ORDER BY e.EST_UF ASC';
        $result = $this->db->fetchAll($query);
        $this->view->estados = $result;
        
        if($uf > 0){
            //$query = 'SELECT SQL_CACHE CID_ID,CID_NOM FROM CIDADES WHERE EST_ID = '.$uf.' ORDER BY CID_NOM ASC';
            $query = 'SELECT SQL_CACHE distinct(c.CID_ID),c.CID_NOM '
                    .' FROM CIDADES c, REVENDA r '
                    .' WHERE c.CID_ID = r.CID_ID AND c.EST_ID = '.$uf.' '
                    .' ORDER BY c.CID_NOM ASC';
            $result = $this->db->fetchAll($query);
            $this->view->cidades = $result;
        }
        
        $query = 'SELECT SQL_CACHE * FROM PAGINA_SITE WHERE PGS_LNK like "%revenda%"';
        $result = $this->db->fetchRow($query);
        $this->view->paginasite = $result;
        
        $where = '';
        
        if($uf > 0) $where .= ' AND EST_ID = '.$uf;
        if($cid > 0) $where .= ' AND CID_ID = '.$cid;
            
        $query = 'SELECT SQL_CACHE * FROM REVENDA WHERE REV_STA = 1 '.$where.' ORDER BY REV_NOM ASC';
        $result = $this->db->fetchAll($query);
        $this->view->result = $result;
    }
    
    public function cidadesAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $html = '<option value="">Cidades</option>';
        $id = $this->_getParam('id', 0);
        if((int) $id > 0 ) {   
            $ok = TRUE;
            
            $query = 'SELECT SQL_CACHE CID_ID,CID_NOM FROM CIDADES WHERE EST_ID = '.$id.' ORDER BY CID_NOM ASC';
            $result = $this->db->fetchAll($query);
            foreach($result as $row){
                $html .= '<option value="'.$row['CID_ID'].'">'.$row['CID_NOM'].'</option>';
            }
        }       
        echo json_encode(array('ok' => $ok, 'html'=> $html));
    }
}

